package com.changgou.util;

import com.changgou.bean.JdContent;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Component
public class pcUtil {

    public static void main(String[] args) throws IOException {
        new pcUtil().parseDataUrl("电脑").forEach(System.out::println);
    }

    public List<JdContent> parseDataUrl( String keyWords) throws IOException{
        ArrayList<JdContent> objescts = new ArrayList<>();
        String urls ="https://search.jd.com/Search?keyword="+keyWords+"&enc=utf-8&wq="+keyWords;
        //  urls = URLEncoder.encode(urls);
        Document document = Jsoup.parse(new URL(urls),30000);
        Element element = document.getElementById("J_goodsList");
        Elements elements = element.getElementsByTag("li");
        for (Element element1 : elements) {
            String imagUrl = element1.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = element1.getElementsByClass("p-price").eq(0).text();
            String title = element1.getElementsByClass("promo-words").eq(0).text();
            JdContent jdContent = new JdContent();
            objescts.add(jdContent);
        }
        return objescts;
    }
}
